﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bop.Dto;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Camc.Quality.OperationHistory;
using System.Web;
using Camc.Quality.Common;
using Camc.Quality.ProductionPlan;

namespace Camc.Quality.Bop
{
    public class BopDescAppService : QualityAppServiceBase
    {
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<OperationLog, Guid> _operationLogRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        public BopDescAppService(IRepository<BopDesc, Guid> bopDescRepository, IRepository<User, long> userRepository,
            IRepository<BopNode, Guid> bopNodeRepository,
            IRepository<OperationLog, Guid> operationLogRepository,
            IRepository<MakeTask, Guid> makeTaskRepository)
        {
            _bopDescRepository = bopDescRepository;
            _userRepository = userRepository;
            _bopNodeRepository = bopNodeRepository;
            _operationLogRepository = operationLogRepository;
            _makeTaskRepository = makeTaskRepository;
        }

        /// <summary>
        /// Bop任务表新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateOrUpdateBopDesc(CreateOrUpdateBopDescInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (string.IsNullOrWhiteSpace(input.BopDesc.ModelName))
            {
                resultMessage.code = 1;
                resultMessage.Message = "名称格式不正确!";
                return resultMessage;
                //throw new UserFriendlyException("名称格式不正确!");
            }
            if (string.IsNullOrWhiteSpace(input.BopDesc.DrawingNo))
            {
                resultMessage.code = 1;
                resultMessage.Message = "图号格式不正确!";
                return resultMessage;
                //throw new UserFriendlyException("图号格式不正确!");
            }
            if (string.IsNullOrWhiteSpace(input.BopDesc.StageSign))
            {
                resultMessage.code = 1;
                resultMessage.Message = "阶段标记格式不正确!";
                return resultMessage;
                //throw new UserFriendlyException("阶段标记格式不正确!");
            }
            if (input.BopDesc.Id == Guid.Empty)
            {
                resultMessage =await CreateBopDesc(input);
            }
            else
            {
                resultMessage = await UpdateBopDesc(input);
            }
            return resultMessage;
        }
        /// <summary>
        /// Bop任务表 更新方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> UpdateBopDesc(CreateOrUpdateBopDescInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var releaseUserId = AbpSession.UserId;
                var bop = await _bopDescRepository.FirstOrDefaultAsync(c => c.Id == input.BopDesc.Id);
                if (input.BopDesc.ModelId != bop.ModelId || input.BopDesc.LotNoId != bop.LotNoId)
                { 
                    var bopDesc= await _bopDescRepository.FirstOrDefaultAsync(d => d.ModelId == input.BopDesc.ModelId && d.LotNoId == input.BopDesc.LotNoId);
                    if (bopDesc != null)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "已存在该型号发次的火箭,不可重复修改！";
                        return resultMessage;
                    }
                }
                string loc = bop.Loc;
                string figure = bop.Figure;
                string color = bop.Color;
                int size = bop.Size;
                string fill = bop.Fill;
                decimal workingHour = bop.WorkingHour;
                //更新 工艺路线节点信息
                var bopNew = ObjectMapper.Map(input.BopDesc, bop);

                bopNew.Loc = loc;
                bopNew.Figure = figure;
                bopNew.Color = color;
                bopNew.Size = size;
                bopNew.Fill = fill;
                bopNew.WorkingHour = workingHour;

                await _bopDescRepository.UpdateAsync(bopNew);
                //增加操作履历
                var users = _userRepository.FirstOrDefaultAsync(p => p.Id == releaseUserId).Result;
                var operationLogDto = new OperationLogDto()
                {
                    BusinessId = input.BopDesc.Id,
                    BusinessType = (BusinessTypes)0,
                    //BusinessTypeDesc = GetEnumName<BusinessType>(0),
                    OperationType = (OperationTypes)2,
                    //OperationTypeDesc = GetEnumName<OperationType>(0),
                    Content = input.BopDesc.ModelName + "任务修改成功",
                    UserName = users.Surname + users.Name
                };
                var operationLog = ObjectMapper.Map<OperationLog>(operationLogDto);
                await _operationLogRepository.InsertAsync(operationLog);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// Bop任务表insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> CreateBopDesc(CreateOrUpdateBopDescInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var bopDesc = await _bopDescRepository.FirstOrDefaultAsync(d => d.ModelId == input.BopDesc.ModelId && d.LotNoId == input.BopDesc.LotNoId);
                if (bopDesc != null)
                {
                    resultMessage.code = 1;
                    resultMessage.Message ="已存在该型号发次的火箭,不可重复创建！";
                    return resultMessage;
                }
                var releaseUserId = AbpSession.UserId;
                //var name = AbpSession.GetUserName();
                double x = -1000;
                double y = 0;
                var bop = new BopDesc()
                {
                    Model = input.BopDesc.Model,
                    ModelName = input.BopDesc.ModelName,
                    LotNo = input.BopDesc.LotNo,
                    DrawingNo = input.BopDesc.DrawingNo,
                    StageSign = input.BopDesc.StageSign,
                    Property = (Properties)(input.BopDesc.Property),
                    ReleaseUserId = releaseUserId,
                    QualityStatus = 0,
                    IsUsed = (Bop.IsUsed)1,
                    ReleaseTime = DateTime.Now,
                    ProcessStatus = ProcessStatus.已创建,
                    WorkingHourStatus = input.BopDesc.WorkingHourStatus,
                    ModelId = input.BopDesc.ModelId,
                    LotNoId = input.BopDesc.LotNoId,
                    Loc = x.ToString() + " " + y.ToString(),
                    Figure = "RoundedRectangle",
                    Color = "black",
                    Size = 0,
                    Fill = "lightgray",
                };
                Guid bopId = await _bopDescRepository.InsertAndGetIdAsync(bop);
                //增加操作履历
                var users = _userRepository.FirstOrDefaultAsync(p => p.Id == releaseUserId).Result;
                var operationLogDto = new OperationLogDto()
                {
                    BusinessId = bopId,
                    BusinessType = (BusinessTypes)0,
                    //BusinessTypeDesc = GetEnumName<BusinessType>(0),
                    OperationType = (OperationTypes)0,
                    //OperationTypeDesc = GetEnumName<OperationType>(0),
                    Content = input.BopDesc.ModelName + "任务创建成功",
                    UserName = users.Surname + users.Name
                };
                var operationLog = ObjectMapper.Map<OperationLog>(operationLogDto);
                await _operationLogRepository.InsertAsync(operationLog);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// Bop任务表 Delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteBopDesc(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //2021.05.15 加个防错，已维护节点信息的不能删除
                var bomNode = await _bopNodeRepository.FirstOrDefaultAsync(x => x.BopDescId == id);
                if (bomNode != null)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "已维护节点信息，不能删除";
                    return resultMessage;
                    //throw new UserFriendlyException("已维护节点信息，不能删除");
                }
                else
                {
                    await _bopDescRepository.DeleteAsync(id);
                    resultMessage.code = 0;
                    return resultMessage;
                }
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// Bop任务表查询，传参是Fliter过滤，模糊查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BopDescOutput>> GetBopDescList(GetBopDescListInput input)
        {
            try
            {
                var query = _bopDescRepository.GetAll().WhereIf(!input.Filter.IsNullOrWhiteSpace(),
                x => x.Model.Contains(input.Filter) ||
                x.LotNo.Contains(input.Filter) ||
                x.ModelName.Contains(input.Filter) ||
                x.StageSign.Contains(input.Filter) ||
                x.DrawingNo.Contains(input.Filter)
                ).WhereIf(!input.Model.IsNullOrWhiteSpace(), x => x.Model.Contains(input.Model)
                ).WhereIf(!input.LotNo.IsNullOrWhiteSpace(), x => x.LotNo.Contains(input.LotNo)
                ).WhereIf(!input.DrawingNO.IsNullOrWhiteSpace(), x => x.DrawingNo.Contains(input.DrawingNO));
                var count = await query.CountAsync();

                var bopDescList = query.OrderBy(input.Sorting).PageBy(input).ToList();
                var list = ObjectMapper.Map<List<BopDescOutput>>(bopDescList);

                var tempData = from cc in _makeTaskRepository.GetAll()
                               select new
                               {
                                   LonoId = cc.LotNoId,
                                   ModelId = cc.ModelId,
                                   RocketState = cc.RocketState,
                               };

                for (int i = 0; i < list.Count(); i++)
                {
                  //  var user = await UserManager.GetUserByIdAsync((long)list[i].CreatorUserId);
                  ////  var user = _userRepository.GetAll().Where(t => t.Id ==);
                  //  list[i].UserName = user.Surname + user.Name;// + user.Name;
                                                                //通过Map实现了
                                                                //item.StatusDesc = ((Status)(item.Status)).ToString();
                                                                //item.QualityStatusDesc= ((QualityStatus)(item.QualityStatus)).ToString();
                    var tempRo = tempData.Where(d => d.LonoId == list[i].LotNoId && d.ModelId == list[i].ModelId).FirstOrDefault();
                    if (tempRo != null)
                    {
                        list[i].RocketState = tempRo.RocketState;
                    }
                }

              
                return new PagedResultDto<BopDescOutput>(count, list);
            }
            catch (Exception e)
            {

                throw;
            }

        }
        /// <summary>
        /// Bop任务表查询 By Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BopDescDto> GetBopDescById(Guid id)
        {
            var bomDesc = await _bopDescRepository.FirstOrDefaultAsync(x => x.Id == id);

            if (bomDesc != null)
            {
                var bopDto = ObjectMapper.Map<BopDescDto>(bomDesc);
                return bopDto;
            }
            else
            {
                return new BopDescDto();
            }
        }
        protected static double NextDouble(double miniDouble, double maxiDouble) 
        {
            Random random = new Random();
            double num = maxiDouble - miniDouble;
            if (num <= double.MaxValue)
            {
                var ran = random.NextDouble();
                var numRes = (ran * (double)num) + miniDouble;
                return numRes;
            }
            int RandNum = random.Next();
            if ((random.Next() % 2 == 0) ? true : false)
            {
                num = -num;
            }
            double num2 = num;
            num2 += 2147483646.0;
            num2 = num2 / 4294967293.0;
            return (num2 * (double)num) + miniDouble;

        }
    }
}
